{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Watch a Deep Q-Network Agent! \n",
    "\n",
    "### 1.Start the Environment "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input_dim:  8 , output_dim:  4 , hidden_dim:  16\n"
     ]
    }
   ],
   "source": [
    "import gym\n",
    "import torch\n",
    "from agent import Agent, FloatTensor\n",
    "import time\n",
    "\n",
    "env = gym.make('LunarLander-v2')\n",
    "\n",
    "state_dim =  env.observation_space.shape[0] # n_spaces =\n",
    "action_dim = env.action_space.n # n_actions = \n",
    "hidden_dim = 16\n",
    "agent = Agent(state_dim, action_dim, hidden_dim)        \n",
    "print('input_dim: ', state_dim, ', output_dim: ', action_dim, ', hidden_dim: ', hidden_dim)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. Prepare Load"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load(agent, directory, filename):\n",
    "    agent.q_local.load_state_dict(torch.load('%s/%s_local.pth' % (directory,  filename)))\n",
    "    agent.q_target.load_state_dict(torch.load('%s/%s_target.pth' % (directory,  filename)))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. Prepare Player"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import deque\n",
    "import os\n",
    "import numpy as np\n",
    "\n",
    "def play(env, agent, n_episodes):\n",
    "    state = env.reset()\n",
    "    \n",
    "    scores_deque = deque(maxlen=100)\n",
    "\n",
    "    for i_episode in range(1, n_episodes+1):\n",
    "        s = env.reset()        \n",
    "        \n",
    "        total_reward = 0\n",
    "        time_start = time.time()\n",
    "        timesteps =  0\n",
    "        \n",
    "        while True:\n",
    "            \n",
    "            a = agent.get_action(FloatTensor([s]), check_eps=False, eps=0.01)\n",
    "            env.render()\n",
    "            s2, r, done, _ = env.step(a.item())\n",
    "            s = s2\n",
    "            total_reward += r\n",
    "            timesteps += 1\n",
    "            \n",
    "            if done:\n",
    "                break \n",
    "\n",
    "        delta = (int)(time.time() - time_start)\n",
    "        \n",
    "        scores_deque.append(total_reward)\n",
    "\n",
    "        print('Episode {}\\tAverage Score: {:.2f}, \\t Timesteps: {} \\tTime: {:02}:{:02}:{:02}'\\\n",
    "                  .format(i_episode, np.mean(scores_deque), timesteps,\\\n",
    "                          delta//3600, delta%3600//60, delta%60))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4. Load and Play"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Episode 1\tAverage Score: 282.86, \t Timesteps: 232 \tTime: 00:00:08\n",
      "Episode 2\tAverage Score: 294.44, \t Timesteps: 242 \tTime: 00:00:04\n",
      "Episode 3\tAverage Score: 288.48, \t Timesteps: 211 \tTime: 00:00:03\n",
      "Episode 4\tAverage Score: 277.02, \t Timesteps: 188 \tTime: 00:00:03\n",
      "Episode 5\tAverage Score: 273.24, \t Timesteps: 243 \tTime: 00:00:04\n",
      "Episode 6\tAverage Score: 277.14, \t Timesteps: 299 \tTime: 00:00:04\n",
      "Episode 7\tAverage Score: 251.95, \t Timesteps: 1000 \tTime: 00:00:16\n",
      "Episode 8\tAverage Score: 240.05, \t Timesteps: 1000 \tTime: 00:00:16\n",
      "Episode 9\tAverage Score: 225.79, \t Timesteps: 1000 \tTime: 00:00:16\n",
      "Episode 10\tAverage Score: 231.14, \t Timesteps: 175 \tTime: 00:00:02\n"
     ]
    }
   ],
   "source": [
    "load(agent, 'dir_chk', 'LunarLander-v2')\n",
    "play(env=env, agent=agent, n_episodes=10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "env.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ml2-kernel",
   "language": "python",
   "name": "ml2-kernel"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
